package io.renren.api;

import io.renren.core.annotation.LoginUser;
import io.renren.entity.Dictionary;
import io.renren.entity.*;
import io.renren.entity.vo.BookVideo4Web;
import io.renren.service.*;
import io.renren.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@RestController
@RequestMapping("/api/video")
public class ApiBookVideoController {

    @Autowired
    private BookService bookService;

    @Autowired
    private BookVideoService bookVideoService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private UserDefaultInfoService userDefaultInfoService;

    /**
     * 根据年级科目教版获取视频列表
     *
     * @return
     */
    @RequestMapping("/getVideoList")
    public R getVideoList(@RequestParam Long gradeId, @RequestParam Long subjectId, @RequestParam Long versionId) {

        //查询用户默认信息
        Map query = new HashMap();
        query.put("gradeId", gradeId);
        query.put("subjectId", subjectId);
        query.put("versionId", versionId);
        query.put("seasonId", ConfigConstant.DEFAULT_SEASON_ID);

        List<Book> bookList = bookService.queryList(query);
        if (bookList == null || bookList.size() == 0) {
            return R.ok();
        }

        List<BookVideo4Web> videoList = getVideoList(bookList);
        videoList = videoList.stream()
                .sorted(Comparator.comparing(BookVideo4Web::getPageNo)
                        .thenComparing(BookVideo4Web::getOrderField))
                .collect(Collectors.toList());

        return R.ok()
                .put("book", bookList.get(0))
                .put("videoList", videoList);
    }

    /**
     * 根据视频id获取视频详情
     *
     * @param videoId
     * @return
     */
    @RequestMapping("/getDetail")
    public R getVideoDetail(@RequestParam Long videoId) {
        BookVideo bookVideo = bookVideoService.queryObject(videoId);
        //获取当前视频后的三个视频
        Map query = new HashMap();
        query.put("status", "1");
        query.put("bookId", bookVideo.getBookId());
        List<BookVideo> bookVideoList = bookVideoService.queryList(query);
        List<BookVideo> moreBookVideoList;

        List<BookVideo> videoList = bookVideoList.stream()
                .sorted(Comparator.comparing(BookVideo::getPageNo)
                        .thenComparing(BookVideo::getOrderField))
                .collect(Collectors.toList());
        List<Long> collect = videoList.stream().map(BookVideo::getId).collect(Collectors.toList());
        int i = collect.indexOf(videoId);
        if (i == collect.size() - 1) {
            moreBookVideoList = videoList.stream().limit(3).collect(Collectors.toList());
        } else {
            moreBookVideoList = videoList.stream().skip(i + 1).limit(3).collect(Collectors.toList());
        }
        return R.ok()
                .put("bookVideo", bookVideo)
                .put("moreBookVideoList", moreBookVideoList);
    }

    /**
     * 根据语音，获取视频列表
     *
     * @param voiceStr
     * @return
     */
    @RequestMapping("/getVideoListByVoice")
    public R getVideoListByVoice(@RequestParam String voiceStr, @LoginUser WxUser wxUser) {

        //根据年级和科目查询列表信息
        List<Dictionary> dictionaryList = dictionaryService.queryList(null);
        dictionaryList = dictionaryList.stream()
                .filter(dictionary -> dictionary.getType().equals("T02") && "1".equals(dictionary.getStatus()) && "0".equals(dictionary.getDeleted()))
                .collect(Collectors.toList());
        String[] subjectAndPageNo = VoiceSearchUtil.SubjectAndPageNoParse(voiceStr, dictionaryList);
        if (subjectAndPageNo[0].length() == 0 || subjectAndPageNo[1].length() == 0) {
            return R.error("格式不对");
        }

        //查询用户默认信息
        Map query = new HashMap();
        query.put("status", "1");
        query.put("deleted", "0");
        query.put("userId", wxUser.getId());
        query.put("gradeId", wxUser.getGradeId());
        query.put("subjectId", subjectAndPageNo[0]);
        query.put("seasonId", ConfigConstant.DEFAULT_SEASON_ID);//获取教辅书信息

        List<UserDefaultInfo> userDefaultInfoList = userDefaultInfoService.queryList(query);

        if (userDefaultInfoList != null && userDefaultInfoList.size() > 0) {
            query.put("versionId", userDefaultInfoList.get(0).getVersionId());
        }
        List<Book> bookList = bookService.queryList(query);
        if (bookList == null || bookList.size() == 0) {
            return R.ok();
        }
        Book book = bookList.get(0);
        String gradeName = book.getGrade().getName();
        String seasonName = book.getSeason().getName();
        String subjectName = book.getSubject().getName();

        String videoInfo = gradeName + ">基础训练>" + subjectName + ">" + seasonName;

        List<BookVideo4Web> videoList = getVideoList(bookList, subjectAndPageNo[1]);
        if (videoList != null) {
            videoList = videoList.stream()
                    .sorted(Comparator.comparing(BookVideo4Web::getPageNo).thenComparing(Comparator.comparing(BookVideo4Web::getOrderField)))
                    .collect(Collectors.toList());
        }

        return R.ok()
                .put("videoInfo", videoInfo)
                .put("videoList", videoList);
    }

    private List<BookVideo4Web> getVideoList(List<Book> bookList) {

        Stream<List<BookVideo4Web>> listStream = bookList.stream()
                .filter(book -> book.getStatus().equals("1") && book.getDeleted().equals("0"))
                .map(book -> {
                            Map videoQuery = new HashMap();
                            videoQuery.put("status", "1");
                            videoQuery.put("deleted", "0");
                            videoQuery.put("bookId", book.getId());
                            List<BookVideo> bookVideoList = bookVideoService.queryList(videoQuery);
                            List<BookVideo4Web> collect = bookVideoList.stream().map(bookVideo -> {
                                BookVideo4Web bookVideo4Web = new BookVideo4Web();
                                bookVideo4Web.setId(bookVideo.getId());
                                bookVideo4Web.setPageNo(bookVideo.getPageNo());
                                bookVideo4Web.setUnitName(bookVideo.getUnitName());
                                bookVideo4Web.setVideoName(bookVideo.getVideoName());
                                bookVideo4Web.setOrderField(bookVideo.getOrderField() == null ? 0 :
                                        bookVideo.getOrderField());
                                return bookVideo4Web;
                            }).collect(Collectors.toList());
                            return collect;
                        }
                ).filter(bookVideo4Webs -> bookVideo4Webs != null && bookVideo4Webs.size() > 0);

        List<BookVideo4Web> bookVideo4WebList = listStream
                .reduce(new ArrayList<>(), (bookVideoList, bookVideoList1) -> {
                            bookVideoList.addAll(bookVideoList1);
                            return bookVideoList;
                        }
                );

        return bookVideo4WebList;
    }

    private List<BookVideo4Web> getVideoList(List<Book> bookList, String pageNo) {
        Stream<List<BookVideo4Web>> listStream = bookList.stream()
                .map(book -> {
                            Map videoQuery = new HashMap();
                            videoQuery.put("status", "1");
                            videoQuery.put("deleted", "0");
                            videoQuery.put("pageNo", pageNo);
                            videoQuery.put("bookId", book.getId());
                            List<BookVideo> bookVideoList = bookVideoService.queryList(videoQuery);
                            List<BookVideo4Web> collect = bookVideoList.stream()
                                    .map(bookVideo -> {
                                        BookVideo4Web bookVideo4Web = new BookVideo4Web();
                                        bookVideo4Web.setId(bookVideo.getId());
                                        bookVideo4Web.setPageNo(bookVideo.getPageNo());
                                        bookVideo4Web.setUnitName(bookVideo.getUnitName());
                                        bookVideo4Web.setVideoName(bookVideo.getVideoName());
                                        bookVideo4Web.setVersionName(book.getVersion().getName());
                                        bookVideo4Web.setOrderField(bookVideo.getOrderField());
                                        return bookVideo4Web;
                                    }).collect(Collectors.toList());
                            return collect;
                        }
                );

        List<BookVideo4Web> bookVideo4WebList = listStream
                .reduce(new ArrayList<>(), (bookVideoList, bookVideoList1) -> {
                            bookVideoList.addAll(bookVideoList1);
                            return bookVideoList;
                        }
                );

        return bookVideo4WebList;
    }

}
